package work.chatmeter;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

import utils.MyUtils;


public class LoginURLCreator {

	private String resellerId = "27";
	private String usernamePrefix = "AptMC";
	private String authURL = "https://www.apartmentratingsreputation.com/public/index/login";
	private String sharedPrivateKey;

	public static void main(String[] args) {
		try {
			Integer userId = 12426;
			System.out.println(new LoginURLCreator().generateAuthenticationURL(userId));
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public LoginURLCreator() {

		InputStream stream = null;

		try {
			stream = new FileInputStream("/home/gmarcone/Carpeta sin título/chatmetersharedkey.txt");
			StringWriter writer = new StringWriter();
			MyUtils.copy(stream, writer);
			sharedPrivateKey = writer.toString();
			sharedPrivateKey = sharedPrivateKey.replaceAll("\r", "");
		} catch (IOException e) {
			e.printStackTrace(System.out);
		} finally {
			try {
				if (null != stream) {
					stream.close();
				}
			} catch (IOException e) {
				e.printStackTrace(System.out);
			}
		}
	}

	public String generateAuthenticationURL(Integer userId) {

		String userName = this.usernamePrefix + userId;
		String hash = generateHash(userName);

		try {
			if (null != hash) {
				String authURL = this.authURL + "?username=" + URLEncoder.encode(userName, "UTF-8");
				authURL += "&resellerid=" + this.resellerId + "&hash=" + URLEncoder.encode(hash, "UTF-8");
				return authURL;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String generateHash(String userName) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			md.reset();
			String msg = userName + sharedPrivateKey;
			md.update(msg.getBytes(Charset.forName("ASCII")));
			final byte[] md5 = md.digest();
			return Hex.encodeHexString(md5);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return null;
	}
}
